package com.im.partchat.adapter.tree;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.im.partchat.R;
import com.im.partchat.bean.Department;
import com.im.partchat.bean.User;
import com.im.partchat.db.dao.DeptDao;
import com.im.partchat.db.dao.UserDao;
import com.im.partchat.widget.GlideCircleTransform;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by lwj on 2015/5/28.
 */
public class TreeItemAdapter extends BaseAdapter implements AdapterView.OnItemClickListener {

    private Context mContext;
    private List<TreeElement> nodesList;
    private boolean showCheckBox = false;
    private ListView listView;
    private TreeItemClickCallBack treeItemClickcallBack;
    private int lastPosition = 0;
    private final HashMap<String, String> MAP_ARRAY = new HashMap<>();
    private CheckBox checkBox;
    private boolean hasHeaderView = false;
    /**
     * 是否单选
     */
    private boolean singleChoose = false;
    /**
     * 数据缓存，用户缓存每一个部门节点下的子节点
     */
    public static final HashMap<String, List<TreeElement>> DATA_CACHE = new HashMap<>();

    public TreeItemAdapter(Context mContext, ListView listView, List<TreeElement> nodes) {
        this.mContext = mContext;
        this.listView = listView;
        if (listView != null) {
            listView.setOnItemClickListener(this);
        }
        this.nodesList = nodes;
        initCache();
    }


    /**
     * 初始化
     */
    private void initCache(){
        if (nodesList != null && !nodesList.isEmpty()) {
            TreeElement treeElement = nodesList.get(0);
            if (treeElement != null && treeElement.isDept()) {
                DATA_CACHE.put(treeElement.getDept().getId(), treeElement.getChildren());
            }
        }
    }

    /**
     * 清除缓存
     */
    public void clearCache() {
        DATA_CACHE.clear();
    }

    public boolean isSingleChoose() {
        return singleChoose;
    }

    public void setSingleChoose(boolean singleChoose) {
        this.singleChoose = singleChoose;
    }

    public boolean isHasHeaderView() {
        return hasHeaderView;
    }

    public void setHasHeaderView(boolean hasHeaderView) {
        this.hasHeaderView = hasHeaderView;
    }

    /**
     * 设置checkBox
     *
     * @param checkBox
     */
    public void setCheckBox(CheckBox checkBox) {
        this.checkBox = checkBox;
        if (this.checkBox != null) {
            this.checkBox.setVisibility(View.VISIBLE);
//            this.checkBox.setOnClickListener(this);
        }
    }



    /**
     * 注入item click 回调
     *
     * @param treeItemClickcallBack
     */
    public void registerTreeItemClickListener(TreeItemClickCallBack treeItemClickcallBack) {
        if (treeItemClickcallBack != null) {
            this.treeItemClickcallBack = treeItemClickcallBack;
        }
    }

    @Override
    public int getCount() {
        if (nodesList == null) {
            return 0;
        }
        return nodesList.size();
    }

    @Override
    public Object getItem(int position) {
        return nodesList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.party_list_item, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.icon = (ImageView) convertView
                    .findViewById(R.id.id_treenode_icon);
            viewHolder.label = (TextView) convertView
                    .findViewById(R.id.id_treenode_label);
            viewHolder.img = (ImageView) convertView
                    .findViewById(R.id.treenode_img);
            viewHolder.tel = (TextView) convertView
                    .findViewById(R.id.id_treenode_tel);
            viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
            viewHolder.item_layout = (RelativeLayout) convertView
                    .findViewById(R.id.item_layout);
            convertView.setTag(viewHolder);

        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        TreeElement obj = nodesList.get(position);
        checkParentState(obj);
        if (obj.isDept()) {
            //有下级菜单
            viewHolder.item_layout.setPadding(32 * obj.getLevel(), 0,
                    0, 0);
            viewHolder.img.setVisibility(View.GONE);//隐藏头像
            viewHolder.tel.setVisibility(View.GONE);//隐藏电话号码
            viewHolder.icon.setVisibility(View.VISIBLE);
            if (obj.isExpanded()) {
                viewHolder.icon.setBackgroundResource(R.drawable.tree_item_open);
            } else {
                viewHolder.icon.setBackgroundResource(R.drawable.tree_item_close);
            }
            setAttribute(viewHolder, true);
            viewHolder.label.setText(obj.getDept().getName());
        } else {
            //没有下级菜单
            int level = obj.getLevel();
            level--;
            if (level < 0) {
                level = 0;
            }
            viewHolder.item_layout.setPadding(32 * level, 28, 0, 28);
            viewHolder.icon.setVisibility(View.GONE);//隐藏图标
            viewHolder.img.setVisibility(View.VISIBLE); //显示头像
            viewHolder.tel.setVisibility(View.VISIBLE);//显示电话号码
            //设置相关资源属性
            setAttribute(viewHolder, false);
            viewHolder.label.setText(obj.getPerson().getName());
            viewHolder.tel.setText(obj.getPerson().getPhone());
            if (!TextUtils.isEmpty(obj.getPerson().getHeadUrl())) {
                Glide.with(mContext)
                        .load(obj.getPerson().getHeadUrl())
                        .transform(new GlideCircleTransform(mContext))
                        .placeholder(R.drawable.rc_ic_def_msg_portrait)
                        .error(R.drawable.rc_ic_def_msg_portrait)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(viewHolder.img);
            } else {
                viewHolder.img.setImageResource(R.drawable.rc_ic_def_msg_portrait);
            }
        }
        if (showCheckBox) {
            if (!obj.isDept() && obj.getPerson() != null) {
                viewHolder.checkBox.setVisibility(View.GONE);
            } else {
                if ((isSingleChoose() && obj.isDept())) {
                    viewHolder.checkBox.setVisibility(View.GONE);
                } else if (obj.isDept() && !hasPersons(obj)) {
                    viewHolder.checkBox.setVisibility(View.GONE);
                } else {
                    viewHolder.checkBox.setVisibility(View.VISIBLE);
                }
            }
        } else {
            viewHolder.checkBox.setVisibility(View.GONE);
        }
        if (!obj.isDept()) {
            viewHolder.checkBox.setClickable(false);
        } else {
            viewHolder.checkBox.setClickable(true);
            viewHolder.checkBox.setTag(obj);
            viewHolder.checkBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CheckBox checkBox = (CheckBox) v;
                    TreeElement treeElement = (TreeElement) v.getTag();
                    treeElement.setChoosed(checkBox.isChecked());
                    setChildrenChecked(treeElement.getChildren(), checkBox.isChecked());
                    if (!singleChoose && treeItemClickcallBack != null) {
                        treeItemClickcallBack.onDeptItemChecked(treeElement.getChildren(), treeElement.isChoosed());
                    }
                    notifyDataSetChanged();
                }
            });
        }
        viewHolder.checkBox.setChecked(obj.isChoosed());
        viewHolder.checkBox.setEnabled(obj.isEnable());
        return convertView;
    }

    private boolean hasPersons(TreeElement obj) {
        if (obj.getChildren() == null || obj.getChildren().isEmpty()) {
            return false;
        }
        List<TreeElement> elements = obj.getChildren();
        for (TreeElement element : elements) {
            if (element != null
                    && element.getPerson() != null) {
                return true;
            } else if (element.isDept()) {
                if (hasPersons(element)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 根据是否有下级，设置相关资源树形
     *
     * @param flag
     * @param viewHolder
     */
    private void setAttribute(ViewHolder viewHolder, boolean flag) {
        if (flag) {
            //有下级菜单
            viewHolder.item_layout.setBackgroundResource(R.drawable.white_background);
            viewHolder.label.setTextSize(14);
        } else {
            //没有下级菜单
            viewHolder.item_layout.setBackgroundResource(R.drawable.white_background);
            viewHolder.label.setTextSize(16);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (nodesList != null) {
            if (isHasHeaderView()) {
                position--;
            }
            TreeElement element = nodesList.get(position);
            if (element != null) {
                //人员 isDept()是否是部门，true是单位，false是部门
                if (!element.isDept()) {
                    //多选状态下
                    if (showCheckBox
                            && element.getPerson() != null) {
                        element.setChoosed(!element.isChoosed());
                        if (singleChoose) {
                            setSingleChooseOperate(element, nodesList);
                        }
                    }
                    //检查状态
                    checkParentState(element);
                    //回调到UI层
                    if (this.treeItemClickcallBack != null) {
                        this.treeItemClickcallBack.onTreeItemClick(view, element);
                    }
                } else if (element.isDept()) { //部门节点
                    //已经展开
                    if (element.isExpanded()) {
                        element.setExpanded(false);
                        ArrayList<TreeElement> temp = new ArrayList<>();
                        for (int i = position + 1; i < nodesList.size(); i++) {
                            if (element.getLevel() >= nodesList.get(i).getLevel()) {
                                break;
                            }
                            temp.add(nodesList.get(i));
                        }
                        nodesList.removeAll(temp);
                        element.setChildren(temp);
                        //没有展开
                    } else {
                        element.setExpanded(true);
                        //如果child为空，那么所有的子节点初始化都设置expand 为false
                        boolean defaultExpand = false;
                        if (element.getChildren() == null || element.getChildren().isEmpty()) {
                            loadChildData(element);
                            defaultExpand = true;
                        }
                        if (element.getChildren() != null && !element.getChildren().isEmpty()) {
                            int i = 0;
                            for (TreeElement child : element.getChildren()) {
                                if (defaultExpand) {
                                    child.setExpanded(false);
                                }
                                if (this.treeItemClickcallBack != null) {
                                    treeItemClickcallBack.onDeptTreeItemClick(child);
                                }
                                nodesList.add(position + (++i), child);
                            }
                        }
                    }
                }
            }
            notifyDataSetChanged();
            listView.smoothScrollToPosition(position + 2);
        }
    }

    /**
     * 点击子节点检查父节点状态
     * @param element
     */
    private void checkParentState(TreeElement element){
        if (element != null && element.getParentNode() != null) {
            List<TreeElement> childs = element.getParentNode().getChildren();
            if (childs != null && !childs.isEmpty()) {
                boolean allChecked = true;
                for (TreeElement treeElement : childs) {
                    if (treeElement.isDept()) {
                        if (hasPersons(treeElement)) {
                            if (!treeElement.isChoosed()) {
                                allChecked = false;
                            }
                        }
                    } else {
                        if (treeElement != null
                                && treeElement.getPerson() != null
                                && !treeElement.isChoosed()) {
                            allChecked = false;
                            break;
                        }
                    }

                }
                if (allChecked) {
                    element.getParentNode().setChoosed(true);
                } else {
                    element.getParentNode().setChoosed(false);
                }
            }
        }
    }

    /**
     * 设置单选，当前被选中的其他已经选中的设置为未选中
     *
     * @param treeElement
     */
    private void setSingleChooseOperate(TreeElement treeElement, List<TreeElement> nodes) {
        if (nodes != null && !nodes.isEmpty()) {
            for (TreeElement node : nodes) {
                if (!node.equals(treeElement)) {
                    node.setChoosed(false);
                    setSingleChooseOperate(treeElement, node.getChildren());
                }
            }
        }
    }

    private void loadChildData(TreeElement parentNode) {
        if (parentNode == null || parentNode.getDept() == null) {
            return;
        }
        List<TreeElement> cacheList = new ArrayList<>();
        List<User> personBeans = UserDao.getInstance().getUserByDeptId(parentNode.getDept().getId());
        List<Department> deptBeans = DeptDao.getInstance().getSubDepart(parentNode.getDept().getId());
        for (User personBean : personBeans) {
            TreeElement element = new TreeElement();
            element.setChoosed(parentNode.isChoosed());
            element.setLevel(parentNode.getLevel() + 1);
            element.setPerson(personBean);
            element.setDept(false);
            element.setParentNode(parentNode);
            cacheList.add(element);
        }
        for (Department deptBean : deptBeans) {
            TreeElement element = new TreeElement();
            element.setChoosed(parentNode.isChoosed());
            element.setLevel(parentNode.getLevel() + 1);
            element.setDept(deptBean);
            element.setParentNode(parentNode);
            element.setDept(true);
            cacheList.add(element);
        }
        parentNode.setHasChild(true);
        parentNode.setChildren(cacheList);
    }

    private boolean isMove(int position){
        if (nodesList != null && !nodesList.isEmpty() && nodesList.size() > (position + 1)) {
            TreeElement nextElement = nodesList.get(position + 1);
            if (nextElement.isDept() &&
                    nextElement.getChildren() != null &&
                    !nextElement.getChildren().isEmpty() && nextElement.isExpanded()) {
                return true;
            }
        }
        return false;
    }

    class ViewHolder {
        ImageView icon; //图标
        TextView label; //姓名
        ImageView img;  //头像
        TextView tel;  //电话
        CheckBox checkBox; //多选复选框
        RelativeLayout item_layout;
    }


    /**
     * lwj 设置是否显示复选框
     *
     * @param showCheckBox
     */
    public void setShowCheckBox(boolean showCheckBox) {
        this.showCheckBox = showCheckBox;
    }

    private void setChildrenChecked(List<TreeElement> nodeList, boolean checked) {
        if (nodeList != null && !nodeList.isEmpty()) {
            for (TreeElement node : nodeList) {
                if (node != null && !node.isDept() && node.getPerson() != null) {
                    continue;
                }
                if (node.isDept()) {
                    if (!hasPersons(node)) {
                        node.setChoosed(false);
                    } else {
                        node.setChoosed(checked);
                    }
                } else {
                    node.setChoosed(checked);
                }
                if (node.getChildren() != null && !node.getChildren().isEmpty()) {
                    setChildrenChecked(node.getChildren(), checked);
                }
            }
        }

    }


    /**
     * tree item 点击回调
     */
    public interface TreeItemClickCallBack {
        void onTreeItemClick(View view, TreeElement element);
        void onDeptTreeItemClick(TreeElement item);
        void onDeptItemChecked(List<TreeElement> items, boolean choosed);
    }


}
